package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.domain.po.BookEntity;
import com.example.demo.domain.po.BorrowEntity;
import com.example.demo.mapper.BorrowMapper;
import com.example.demo.service.BookService;
import com.example.demo.service.BorrowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.util.List;

@Service
public class BorrowServiceImpl extends ServiceImpl<BorrowMapper, BorrowEntity> implements BorrowService {
    @Autowired
    private BookService bookService;
    @Autowired
    private BorrowMapper borrowMapper;
    public List<BorrowEntity> getBorrowsByUserName(String username){
        QueryWrapper<BorrowEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        return this.list(wrapper);
    }

    public List<BorrowEntity> getBorrowsByBookID(Long bookID){
        QueryWrapper<BorrowEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("bookID", bookID);
        return this.list(wrapper);
    }
    public List<BorrowEntity> getBorrows(){
        List<BorrowEntity> bList = this.list();
        return bList;
    }
    public List<BorrowEntity> getBorrowsByBookName(String bookName){
        QueryWrapper<BorrowEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("bookName", bookName);
        return this.list(wrapper);
    }


    public BorrowEntity addBorrow(BorrowEntity borrowEntity){
        BookEntity book = borrowMapper.queryBookByBookName(borrowEntity.getBookName());
        if(book.getBorrowed() == 1)
            return null;
        //更新借阅状态
        book.setBorrowed(1);
        bookService.updateBook(book);
        BorrowEntity borrow;
        // 获取当前时间的毫秒数
        long currentTimeMillis = System.currentTimeMillis();

        // 创建 java.sql.Date 对象，使用当前时间的毫秒数作为参数
        Date currentTime = new Date(currentTimeMillis);
        borrowEntity.setStart(currentTime);
        borrowEntity.setNewEnd(0);
        this.save(borrowEntity);
        borrow = borrowEntity;
        return borrow;
    }
    public boolean updateBorrowEnd(int id, int day){
        BorrowEntity borrowEntity = this.getById(id);
        borrowEntity.setNewEnd(day);
        this.updateById(borrowEntity);
        return true;
    }
    public int deleteBorrow(BorrowEntity borrowEntity){
        //获取图书
        BookEntity book = bookService.getBookByBookName(borrowEntity.getBookName());
        //更新借阅状态
        book.setBorrowed(0);
        bookService.updateBook(book);
        return this.getBaseMapper().deleteById(borrowEntity);
    }

    @Override
    public BookEntity queryBookByBookName(String bookName) {
        BookEntity book = borrowMapper.queryBookByBookName(bookName);
        return book;
    }
}
